// index.js
let myRequest = require('../../common/script/myRequest.js');
let api = require('../../common/script/api.js');
let login = require('../../common/script/login');
const app = getApp()
let wxbarcode = require('../../utils/wxbarcode/index.js')
var timeOut = null //倒计时函数
Page({
  /**
   * 页面的初始数据
   */
  data: {
    member_card: null,
    isVip: true,
    time: 3000,
    isfoundingmember: false,
    refreshBtn: false,
    selectAddressData: [],
    toggle: false,
    phone: '',
    phone_sign: '',
    address: '',
    cardnumber: '',
    totalamount: 0,
    encryptStr: ''

  },

  //获取会员信息
  getCardinfoData() {
    const that = this;
    myRequest.EasyHttp.post(api.reqUrls.membercardShow).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        that.setData({
          isfoundingmember: res.data.result.member_data.isfoundingmember,
          isVip: true,
          totalamount: res.data.result.member_data.totalamount,
          cardnumber: res.data.result.member_data.cardnumber,
        })
        that.getData()
        wx.setStorageSync('isVip', true)
        wx.setStorageSync('refresh', false)
        wx.setStorageSync('memberData', res.data.result.member_data)
        wx.setStorageSync('isfoundingmember', res.data.result.member_data.isfoundingmember)
        wx.setStorageSync('cardnumber', res.data.result.member_data.cardnumber)
        wx.setStorageSync('totalamount', res.data.result.member_data.totalamount)
      } else if (res.data.status == -2) {
        wx.setStorageSync('isVip', false)
        wx.setStorageSync('refresh', false)
        wx.setStorageSync('memberData', null)
        wx.setStorageSync('isfoundingmember', false)
        wx.setStorageSync('cardnumber', '')
        wx.setStorageSync('totalamount', 0)
        that.setData({
          isVip: false,
          isfoundingmember: false,
          cardnumber: '',
          totalamount: 0
        })

      }
    })
  },
  //充值金额
  toTecharge() {
    const that = this;
    if (!that.data.isVip) {
      wx.showToast({
        title: '请绑定会员卡',
        icon: 'error',
        duration: 2000
      })
      return
    }
    clearTimeout(timeOut)
    wx.navigateTo({
      url: `/member/pages/recharge/recharge`,
    })
  },
  // 消费记录
  toSpending() {
    const that = this;
    if (!that.data.isVip) {
      wx.showToast({
        title: '请绑定会员卡',
        icon: 'error',
        duration: 2000
      })
      return
    }
    clearTimeout(timeOut)
    wx.navigateTo({
      url: `/member/pages/spending/spending`,
    })
  },
  //绑定手机号
  getPhoneNumber(e) {
    const that = this;
    if (e.detail.errMsg == 'getPhoneNumber:ok') {
      let data = {
        code: e.detail.code,
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
      }
      wx.showLoading({
        title: '加载中...',
      })
      myRequest.EasyHttp.post(api.reqUrls.getMiniPhone, data).then(res => {
        if (res.data.status == 1) {
          that.setData({
            phone: res.data.phoneinfo.mobile,
            phone_sign: res.data.phoneinfo.phone_sign
          })
          // that.getSite()
          that.applyVirtual()
        } else {
          wx.hideLoading();
          wx.showModal({
            showCancel: false,
            content: res.data.message,
            success(res) {
              if (res.confirm) {

              }
            }
          })
        }
      })
    } else {
      if (e.detail.errno == '104') {
        wx.showToast({
          title: '10秒后可以点击',
          icon: 'error',
          duration: 2000
        })
      }
    }
  },
  getSite() {
    const that = this;
    myRequest.EasyHttp.post(api.reqUrls.getRegisterMemberSelectAddress).then(res => {
      wx.hideLoading();
      if (res.data.status == 1) {
        that.setData({
          selectAddressData: res.data.result.address
        })
        that.onToggle()
      }

    })
  },
  // 显示弹窗
  onToggle() {
    const that = this;
    that.setData({
      toggle: true
    })
  },
  // 关闭弹窗
  onCloseToggle() {
    const that = this;
    that.setData({
      toggle: false,
    })
  },
  bindSelectAddress(e) {
    const that = this;
    let index = e.detail.value[0]
    that.setData({
      address: that.data.selectAddressData[index]
    })
  },
  // 申请会员卡
  applyVirtual() {
    const that = this;
    that.onCloseToggle()
    let phone = that.data.phone;
    let phone_sign = that.data.phone_sign;
    let address = that.data.address;
    let data = {
      phone,
      phone_sign,
      address
    }
    wx.showLoading({
      title: '加载中...',
    })
    myRequest.EasyHttp.post(api.reqUrls.applyVirtualCard, data).then(res => {
      if (res.data.status == 1) {
        wx.showToast({
          title: res.data.msg,
          icon: 'success',
          duration: 2000
        })

        that.getCardinfoData()
      } else if (res.data.status == 2) {

        let itemList = []
        res.data.result.member_list.forEach(item => {
          itemList.push('卡号：' + item.cardnumber + ' ' + '余额：' + item.totalamount)
        })
        wx.showActionSheet({
          alertText: '请选择要绑定的会员卡',
          itemList: itemList,
          success(prop) {
            let data = {
              unique_id: wx.getStorageSync('token'),
              cardnumber: res.data.result.member_list[prop.tapIndex].cardnumber,
              phone,
              phone_sign,
              code: '',
            }
            wx.showLoading({
              title: '加载中...',
            })
            myRequest.EasyHttp.post(api.reqUrls.membercardBind, data).then(res => {
              if (res.data.status == 1) {
                wx.showToast({
                  title: res.data.msg,
                  icon: 'success',
                  duration: 2000
                })
                that.getCardinfoData()
              } else {
                wx.hideLoading();
                wx.showModal({
                  content: res.data.msg,
                  showCancel: false,
                  confirmText: '我知道了',
                  confirmColor: '#ff5151',
                  success(e) {}
                })
              }
            })
          },
          fail(prop) {
            wx.hideLoading();
            console.log(prop.errMsg)
          }
        })

      } else {
        wx.hideLoading();
        wx.showModal({
          showCancel: false,
          content: res.data.msg,
          success(res) {
            if (res.confirm) {

            }
          }
        })
      }
    })
  },
  getData(encrypt_str = '') {
    let that = this;
    let data = {
      encrypt_str,
      cardnumber: that.data.cardnumber,
      ali_appid: '',
      ali_openid: ''
    }
    clearTimeout(timeOut)
    myRequest.EasyHttp.post(api.reqUrls.refreshMember, data).then(res => {
      wx.stopPullDownRefresh();
      wx.hideNavigationBarLoading();
      if (res.data.status == 1) {
        that.setData({
          time: res.data.result.interval * 1000,
          encryptStr: res.data.result.encryptStr
        })
        if (res.data.result.refreshCard) {
          that.getCardinfoData()

        }
        if (Object.keys(res.data.result.notification).length === 0 || res.data.result.notification.status != 1) {
          if (res.data.result.refresh) {
            if (res.data.result.encryptStr) {
              setTimeout(() => {
                that.barCode(res.data.result.encryptStr)
                that.qrCode(res.data.result.encryptStr)
                wx.hideLoading();
              }, 500)
            } else {
              that.setData({
                refreshBtn: true
              })
            }
          } else {
            wx.hideLoading();
          }
          timeOut = setTimeout(() => {
            that.getData(res.data.result.encryptStr)
          }, that.data.time)
        } else {
          wx.setStorageSync('refresh', true)
          let memberCardCode = res.data.result.notification.information.memberCardCode
          let saleMode = res.data.result.notification.information.saleMode
          let orgname = res.data.result.notification.information.orgname
          let money = res.data.result.notification.information.money
          clearTimeout(timeOut)
          wx.navigateTo({
            url: `/member/pages/paymentSuccess/paymentSuccess?memberCardCode=${memberCardCode}&money=${money}&saleMode=${saleMode}&orgname=${orgname}`,
          })
        }
      } else if (res.data.status == -2) {
        wx.hideLoading();
        wx.showToast({
          title: res.data.msg,
          icon: 'error',
          duration: 2000
        })
      } else {
        wx.hideLoading();
        wx.showToast({
          title: res.data.msg,
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
  //刷新二维码
  onQr() {
    const that = this;
    that.setData({
      refreshBtn: false,
    })
    that.getData()
  },
  barCode(code) {
    const query = this.createSelectorQuery()
    const intersectionObserver = this.createIntersectionObserver()
    query.select('#barcode').fields({
      node: true,
      size: true
    }).exec(res => {
      const canvas = res[0].node
      const ctx = canvas.getContext('2d')
      const width = res[0].width
      const height = res[0].height
      // 初始化画布大小
      const dpr = wx.getWindowInfo().pixelRatio
      canvas.width = width * dpr
      canvas.height = height * dpr
      ctx.scale(dpr, dpr)
      wxbarcode.barcode(ctx, {
        code: code,
        width: 750,
        height: 120,
        fgcolor: '#222222',
        bgcolor: '#ffffff',

      });
    })
  },
  qrCode(code) {
    const query = this.createSelectorQuery()
    query.select('#qrcode').fields({
      node: true,
      size: true
    }).exec(res => {
      const canvas = res[0].node
      wxbarcode.wxqrcode({
        canvas: canvas,
        canvasId: 'qrcode',
        width: 260,
        padding: 50,
        paddingColor: '#fff',
        background: '#fff',
        foreground: '#000000',
        text: code,
      });
    })
  },
  // 刷新
  refreshBtn() {
    const that = this;
    wx.showLoading({
      title: '加载中...',
    })
    clearTimeout(timeOut)
    that.onCloseToggle()
    that.getCardinfoData()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const that = this;
    wx.setStorageSync('refresh', true)
    // login.checkLogin().then(res => {
    //   that.getCardinfoData()
    // }).catch(err => {
    //   app.appCallBack = (e) => {
    //     that.getCardinfoData()
    //   }
    // })
  },
  //

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const that = this;
    // that.getVipMsg()
    login.checkLogin().then(res => {
      that.getCardInfo()
    }).catch(err => {
      app.appCallBack = (e) => {
        that.getCardInfo()
      }
    })
  },
  getCardInfo() {
    const that = this;
    const refresh = wx.getStorageSync('refresh');
    if (refresh === true) {
      that.getCardinfoData()
    } else {
      that.getVipMsg()
    }
  },
  getVipMsg() {
    const that = this;
    const refresh = wx.getStorageSync('refresh');
    const isVip = wx.getStorageSync('isVip');
    const isfoundingmember = wx.getStorageSync('isfoundingmember');
    const cardnumber = wx.getStorageSync('cardnumber');
    const totalamount = wx.getStorageSync('totalamount');
    if (isVip) {
      // if (refresh) {
      //   that.getCardinfoData()
      // } else {
      that.setData({
        cardnumber,
        isVip,
        isfoundingmember,
        totalamount
      })
      that.getData(that.data.encryptStr)
      // }
    } else {
      that.setData({
        cardnumber,
        isVip,
        isfoundingmember,
        totalamount
      })
    }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    const that = this;
    clearTimeout(timeOut)
    that.onCloseToggle()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    const that = this;
    clearTimeout(timeOut)
    that.onCloseToggle()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    const that = this;
    clearTimeout(timeOut)
    that.onCloseToggle()
    that.getCardinfoData()

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})